

import random
from datetime import datetime
from project01.mysql import Mysql

# 1. 实现一个登录函数
def login(username,password):
    db_username = 'admin'
    db_password = '123456'

    # 判断用户名或密码是否为空
    if username is None or username == "":
        return {'code':1,'message':'用户名不能为空!'}
    if password is None or password == "":
        return {'code':2,'message':'密码不能为空!'}

    # 用户名和密码正确匹配
    if username == db_username and password == db_password:
        return {'code':0,'message':'登录成功'}

    return {'code':3,'message':'用户名或密码不正确!'}


# 将日期返回成字符串 2023-08-17 11:31:09
def str_date():
    now = datetime.now()
    date_str = now.strftime("%Y-%m-%d %H:%M:%S")
    return date_str


# 实现日期转化 ：将日期转化为字符串

# 编写一个学生的类
class Students:

    def __init__(self,mysql):
        self.mysql = mysql

    # 新增学生
    def add_student(self,studentNo,name,**kwargs):
        # 判断是否输入了必填项
        if studentNo is None or studentNo == "":
            return {"code":11,"message":"学生编号不能为空"}
        if name is None or name == "":
            return {"code":12,"message":"学生姓名不能为空"}
        # 判断学生年龄在0~120岁
        age = kwargs.get('age')
        if not str(age).isdigit():
            return {"code":13,"message":"输入年龄类型不正确"}
        if not 0 <= int(age) <= 120:
            return {"code":14,"message":"输入年龄不符合要求"}
        # 判断学生性别只包含男和女
        # 判断身份证是18位

        sex = kwargs.get('sex')
        s_class = kwargs.get('class')
        card = kwargs.get('card')
        city = kwargs.get('city')
        # 添加学生信息
        sql = "insert into students values('{}','{}','{}','{}','{}','{}','{}')".format(studentNo,name,age,sex,s_class,card,city)
        self.mysql.execute(sql)
        return {"code":10,"message":"添加学生成功","add_time":str_date()}


    # 修改学生
    def edit_student(self,studentNo,**kwargs):
        # 判断传入的编号是否正确
        if not str(studentNo).isdigit():
            return {"code":21,"message":"输入学生编号不正确,请重新输入"}

        if studentNo is None or studentNo == "":
            print({"code": 22, "message": "学生编号不能为空"})

        # 用户传入id是否在已知数据中，若找到，将字典中数据更新，
        sql = "update students set "
        student_no = int(studentNo)     # 获取的编号
        name = kwargs.get('name')
        if name:
            sql += "name = '{}'"
        age = kwargs.get('age')
        if age:
            sql += "age = '{}'"
        sex = kwargs.get('sex')
        if sex:
            sql += "sex = '{}'"
        s_class = kwargs.get('class')
        if s_class:
            sql += "class = '{}'"
        card = kwargs.get('card')
        if card:
            sql += "card='{}'"
        city = kwargs.get('city')
        if city:
            sql += "city='{}'"
        sql += " where studentNo = '{}'"
        print("拼接的SQL语句:{}".format(sql))
        sql.format(name,age,sex,s_class,card,city,student_no)
        rownow = self.mysql.execute(sql)
        if rownow:
            return {"code":20,"message":"编辑成功","update_time":str_date()}
        return {"code":23,"message":"没有找到所要编辑的数据"}


    # 删除学生
    def del_student(self,studentNo):
        # 判断传入的编号是否正确
        if not str(studentNo).isdigit():
            return {"code": 21, "message": "输入学生编号不正确,请重新输入"}

        if studentNo is None or studentNo == "":
            print({"code": 22, "message": "学生编号不能为空"})

        student_no = int(studentNo)
        sql = "delete from students where studentNo = '{}'".format(studentNo)
        self.mysql.execute(sql)
        return {"code":30,"message":"删除成功","delete_time":str_date()}




    # 查询学生
    def search_sutdent(self,name):

        sql = "select * from students where name like '%{}%'".format(name)
        result = self.mysql.get_data(sql)
        if result:
            return {"code": "40", "message": "查询学生成功!", "records": result, "search_time": str_date()}
        return {"code":41,"message":"未查询到任何学生记录"}





if __name__ == '__main__':
    result = None
    mysql = Mysql()
    s = Students(mysql)

    # 进行循环
    flag = True
    while flag:
        vls = input("请输入对应编号进行操作:"
                    "\n 1:) 进行登录"
                    "\n i:) 新增学生信息"
                    "\n u:) 修改学生信息"
                    "\n d:) 删除学生信息"
                    "\n s:) 查询学生信息"
                    "\n q:) 退出操作")

        # 判断用户输入字符是否符合要求
        if not vls in ('1','q','quit','i','u','d','s'):
            continue

        # 进行登录
        if vls == '1':
            username = input("请输入用户名:")
            password = input("请输入密码:")
            result = login(username,password)
            print(result)

        # 新增学生信息
        if vls == "i":
            # 判断是否登录
            if result is None or result.get('code') != 0:
                print({"code":4,"message":"用户未登录，请先进行登录操作!"})
                continue
            student_no = input("请输入学生编号:")
            name = input("请输入学生姓名:")
            age = input("请输入学生年龄:")
            sex = input("请输入学生性别:")
            s_class = input("请输入学生班级:")
            card = input("请输入学生身份证号:")
            city = input("请输入学生城市:")

            s_dict = {'age':age,'sex':sex,'class':s_class,'card':card,'city':city}
            # 调用新增学生方法
            add_result = s.add_student(student_no,name,**s_dict)
            print(add_result)

        # 编辑学生信息
        if vls in ('u','U','update'):
            if result is None or result.get('code') != 0:
                print({"code":4,"message":"用户未登录，请先进行登录操作!"})
                continue
            student_no = input("请输入学生编号:")
            name = input("请输入学生姓名:")
            age = input("请输入学生年龄:")
            sex = input("请输入学生性别:")
            s_class = input("请输入学生班级:")
            card = input("请输入学生身份证:")
            city = input("请输入学生城市:")

            edit_dict = {"studentNo":student_no}
            if name != "":
                edit_dict['name'] = name
            if age != "":
                edit_dict['age'] = age
            if sex != "":
                edit_dict['sex'] = sex
            if s_class != "":
                edit_dict['class'] = s_class
            if card != "":
                edit_dict['card'] = card
            if city != "":
                edit_dict['city'] = city

            edit_result = s.edit_student(**edit_dict)
            print(edit_result)

        # 删除
        if vls in ('d','D','delete'):
            if result is None or result.get('code') != 0:
                print({"code": 4, "message": "用户未登录，请先进行登录操作!"})
                continue
            student_no = input("请输入学生编号:")
            del_result = s.del_student(student_no)
            print(del_result)

        # 查询
        if vls in ('s','S','search'):
            if result is None or result.get('code') != 0:
                print({"code": 4, "message": "用户未登录，请先进行登录操作!"})
                continue
            name = input("请输入学生姓名:")
            search_result = s.search_sutdent(name)
            print(search_result)


        if vls in ('q','quit'):
            flag = False
    mysql.close()